<template>
  <div>
    <basic-layout title="办公用品申请" @handleAdd="handleAdd" :showFilterBtn="true"
      @handleFilter="$refs.queryPopupRef.show = true">
      <div class="columnFlex">
        <!-- 查询条件 -->
        <!-- <van-row class="search-row">
          <van-search v-model="formData.keyWord" maxlength="20" show-action placeholder="申请编号/申请人名称/电话"
            @search="onRefresh">
            <template #action>
              <div @click="onRefresh">搜索</div>
            </template>
          </van-search>
          <div class="filter-icon">
            <van-icon name="filter-o" @click="$refs.queryPopupRef.show = true" />
          </div>
        </van-row> -->
        <!-- 列表 -->
        <van-row class="listCon">
          <van-pull-refresh class="pullRefresh" v-model="refreshLoading" @refresh="onRefresh">
            <van-list v-model="loading" :finished="finished" :finished-text="listData.length ? '没有更多了' : ''"
              @load="onLoad">
              <van-swipe-cell v-for="val in listData" :key="val.officeAppId">
                <div class="cellContent" @click="handleDetail(val)">
                  <div class="top">
                    <div class="flexTit">
                      <p class="title">{{ val.appNo }}</p>
                      <p class="other">
                        <span class="status" :class="'status' + val.appStatus">{{ val.appStatusName }}</span>
                      </p>
                    </div>
                  </div>
                  <div class="bottom">
                    <div class="left">
                      <p>
                        <span class="label">申请人：</span>
                        {{ val.applnt || "-" }}
                      </p>
                      <p>
                        <span class="label">联系方式：</span>
                        {{ $infoHiding.handlePhone(val.applntPhone) }}
                      </p>
                      <p>
                        <span class="label">申请时间：</span>
                        {{ val.appTime || "-" }}
                      </p>
                    </div>
                    <div class="right" v-if="val.appStatus === '10'">
                      <van-button color="#f25454" plain round size="mini" @click="handleCancel(val)">取消申请</van-button>
                    </div>
                  </div>
                </div>
              </van-swipe-cell>
            </van-list>
            <van-empty v-if="!loading && !listData.length" class="custom-image"
              :image="require('../../../../assets/images/empty.png')" description="暂无数据" />
          </van-pull-refresh>
        </van-row>
      </div>
    </basic-layout>
    <!-- 筛选条件弹出框 -->
    <queryPopup ref="queryPopupRef" @handleSearch="defineSearch" @handleReset="handleReset">
      <van-form class="filterBox">
        <label>关键字</label>
        <van-field clearable v-model="formData.keyWord" placeholder="申请编号/申请人名称/电话" />
        <label>申请状态：</label>
        <van-field>
          <template #input>
            <div class="textCon" @click="showPicker = true">
              <span v-if="!canteenText" style="color: #aaa">请选择申请状态</span>
              <span v-else>{{ canteenText }}</span>
            </div>
          </template>
        </van-field>
        <label>申请日期</label>
        <van-field>
          <template #input>
            <div class="textCon" @click="showTimePicker = true">
              <span v-if="!formData.appTime" style="color: #aaa">请选择申请日期</span>
              <span v-else>{{ formData.appTime }}</span>
            </div>
          </template>
          <template #button>
            <van-icon v-if="formData.appTime" name="cross" @click="clearPicker()" />
          </template>
        </van-field>
      </van-form>
    </queryPopup>
    <!-- 申请状态选择 -->
    <van-action-sheet v-model="showPicker" cancel-text="取消" :actions="appStatusList" @select="onConfirm" />
    <!-- 申请日期 -->
    <van-calendar v-model="showTimePicker" :allow-same-day="true" :min-date="minDate" :max-date="maxDate"
      :show-confirm="false" type="range" @confirm="onTimeConfirm" />
    <!-- 新增/详情/编辑 弹出框 -->
    <fullscreenModal :modal="fullscreenModal" :isAdd="isAdd" label="办公用品申请" :editType="editType" :isShowEdit="false"
      :showSave="false" @handleClose="fullscreenModal = false" @handleCancel="editType = 'detail'"
      @handleSave="$refs.editFormRef.handleSave()">
      <detail-form v-show="editType == 'detail'" @close="fullscreenModal = false" ref="detailFormRef"
        @refresh="onRefresh" />
      <edit-form v-show="editType == 'edit'" @close="fullscreenModal = false" ref="editFormRef" @refresh="onRefresh" />
    </fullscreenModal>
    <full-loading v-if="fullLoading"></full-loading>
  </div>
</template>

<script>
import { queryDic } from "@/api/common";
import { getPageForApplys, getById, del, cancel } from "@/api/srvAssurance/officearticles/apply/apply";
import editForm from "./editForm.vue";
import detailForm from "./detailForm.vue";
export default {
  components: { editForm, detailForm },
  data() {
    return {
      currentParam: {}, // 保存当前查看详情的row数据
      loading: false,
      fullLoading: false,
      refreshLoading: false,
      fullscreenModal: false,
      showPicker: false,
      showTimePicker: false,
      showCancelModal: false,
      finished: false,
      formData: {
        keyWord: '',
        appTime: '',
        appTimeStart: '',
        appTimeEnd: '',
        appStatus: '',
        pageNum: 1,
        pageSize: 20
      },
      minDate: new Date(new Date().getFullYear() - 1, 0, 1),
      maxDate: new Date(new Date().getFullYear(), 11, 31),
      canteenText: "",
      listData: [], // 列表数据
      appStatusList: [], // 申请状态列表
      isAdd: false,
      editType: "",
      cancelFormData: {
        officeAppId: '', // 取消标识
        cancelReason: '', // 取消原因
      }
    };
  },
  created() {
    this.getListData();
  },
  mounted() {
    this.queryDicData();
  },
  methods: {
    // 获取表格数据
    getListData() {
      this.loading = true;
      getPageForApplys(this.formData).then((res) => {
        this.loading = false;
        if (res.code === 1000 && res.data) {
          this.listData = [...this.listData, ...res.data.records];
          if (this.listData.length >= res.data.total) {
            this.finished = true;
          }
        } else {
          this.finished = true;
        }
      }).catch(() => {
        this.loading = false;
        this.finished = true;
      });
    },
    // 确定筛选
    defineSearch() {
      this.$refs.queryPopupRef.show = false;
      this.onRefresh()
    },
    onRefresh() {
      this.refreshLoading = false;
      this.finished = false;
      this.listData = [];
      this.formData.pageNum = 1;
      this.getListData();
    },
    onLoad() {
      this.formData.pageNum++;
      this.getListData();
    },
    // 重置
    handleReset() {
      this.formData = {
        keyWord: '',
        appTime: '',
        appTimeStart: '',
        appTimeEnd: '',
        appStatus: '',
        pageNum: 1,
        pageSize: 20
      };
      this.canteenText = "";
      this.onRefresh();
    },
    //申请状态选择
    onConfirm(item) {
      this.formData.appStatus = item.codeValue;
      this.canteenText = item.valueAlias;
      this.showPicker = false;
    },
    //日期格式
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() < 9
        ? "0" + (date.getMonth() + 1)
        : "" + (date.getMonth() + 1)
        }-${date.getDate() < 10 ? "0" + date.getDate() : "" + date.getDate()} 00:00`;
    },
    // 申请日期选择
    onTimeConfirm(date) {
      this.formData.appTimeStart = this.formatDate(date[0]);
      this.formData.appTimeEnd = this.formatDate(date[1]);

      this.formData.appTime = `${this.formatDate(date[0])} / ${this.formatDate(date[1])}`;
      this.showTimePicker = false;
    },
    // 清空查询条件
    clearPicker() {
      this.formData.appTime = "";
      this.formData.appTimeStart = "";
      this.formData.appTimeEnd = "";
      this.onRefresh();
    },
    // 新建数据
    handleAdd() {
      this.fullscreenModal = true;
      this.editType = "edit";
      this.isAdd = true;
      this.$refs.editFormRef.resetForm();
      this.$refs.editFormRef.setappUserInfo();
      this.currentParam = {};
    },
    // 查看详情
    async handleDetail(param) {
      this.fullscreenModal = true;
      this.editType = "detail";
      this.isAdd = false;
      let item = param;
      let res = await getById(param.officeAppId);
      if (res.code == "1000" && res.data) {
        item = res.data;
        this.currentParam = res.data;
        this.$refs.detailFormRef.getData(item);
        this.$refs.detailFormRef.getTestData(res.data.officeAppDetailList);
      } else {
        this.loading = false;
        this.$Notify({ type: "error", message: "详情查询失败！" });
      }
    },
    // 编辑数据
    handleUpdate() {
      this.fullscreenModal = true;
      this.editType = "edit";
      this.$refs.editFormRef.resetForm();
      this.$refs.editFormRef.getData(this.currentParam);
    },
    // 删除
    handleDelete(val) {
      if (val.appStatus != "1") {
        this.$Notify({
          type: "warning",
          message: "该数据已提交在流程中，无法删除！",
        });
        return;
      }
      this.$Dialog.confirm({ title: "是否确定删除该数据？", }).then(async () => {
        var res = await del([val.officeAppId]);
        if (res.code === 1000) {
          this.$Notify({ type: "success", message: "删除成功！" });
          this.onRefresh();
        }
      }).catch(() => { });
    },
    // 取消
    handleCancel(item) {
      this.$Dialog.confirm({ title: "是否确定取消？", }).then(async () => {
        var res = await cancel(item.officeAppId);
        if (res.code === 1000) {
          this.$Notify({ type: "success", message: "取消成功！" });
          this.onRefresh();
        }
      }).catch(() => { });
    },

    // 确定取消
    // handleSure(action, done) {
    //   if (action === 'confirm') {
    //     done(false);
    //     if (!this.cancelFormData.cancelReason) {
    //       this.$Notify({ type: "warning", message: "请输入取消原因" });
    //       return;
    //     } else if (!this.$commonReg.textAreaReg.test(this.cancelFormData.cancelReason)) {
    //       this.$Notify({ type: "warning", message: this.$commonReg.textAreaMsg });
    //       return;
    //     }
    //     this.fullLoading = true;
    //     // editBookState(this.cancelFormData).then(res => {
    //     //   this.fullLoading = false;
    //     //   if (res.code === 1000) {
    //     //     this.showCancelModal = false;
    //     //     this.$Notify({ type: 'success', message: '取消成功！' });
    //     //     this.onRefresh()
    //     //   }
    //     // }).catch(() => {
    //     //   this.fullLoading = false;
    //     // });
    //   } else {
    //     done();
    //   }
    // },
    // 下拉框数据
    queryDicData() {
      queryDic('SA_OFFICE_APP_STATUS_CODE').then(res => {
        if (res.code == 1000) {
          this.appStatusList = res.data
        }
      })
    }
  },
};
</script>

<style scoped lang="less">
.listCon {
  .cellContent {
    .top {
      padding: 0 10px;
      box-sizing: border-box;
      border-bottom: 1px solid #eee;
    }

    .bottom {
      padding: 5px 10px;
      box-sizing: border-box;
      display: flex;
      overflow: hidden;
      align-items: center;

      .left {
        flex: 1;
        overflow: hidden;
      }

      .right {
        margin-left: 10px;

        img {
          width: 35px;
          height: 35px;
          display: block;
          margin: 0 auto 10px;
        }

        .van-button--mini {
          border-radius: 3px;
        }
      }
    }

    .flexTit {
      .other {
        text-align: right;

        .status {
          border-radius: 2px;
          padding: 3px 6px;
          color: green;
          // background: #dbf7db;
        }

        .status2 {
          border-radius: 2px;
          padding: 3px 6px;
          color: green;
          // background: #dbeff7;
        }

        .status1 {
          color: red;
          // background: #f9dbe7;
        }

        .status4 {
          color: red;
          // background: #f9dbe7;
        }
      }
    }

    .people {
      color: #bbb;
      font-size: 12px;
    }
  }
}
</style>